package com.java.comprehensive.design.structural_model.proxy_pattern.cglib_proxy_pattern;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 代理对象工厂
 * 获取代理对象
 */
public class ProxyFactory implements MethodInterceptor {

    private TrainStation trainStation = new TrainStation();

    public TrainStation getProxyObject() {
        //创建Enhancer 对象，类似于JDK代理中的Proxy对象
        Enhancer enhancer = new Enhancer();
        //设置父类字节码对像
        enhancer.setSuperclass(TrainStation.class);
        //设置回调函数
        enhancer.setCallback(this);
        //创建代理对象
        return (TrainStation) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("--------------------intercept执行了--------------------");
        System.out.println("代售点收取服务费（CGLIB动态代理）");
        Object invoke = method.invoke(trainStation, objects);
        return invoke;
    }
}
